package com.test.realcityalfa.activityswitchers;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;

public class ActivitySwitch extends Thread
{
	private volatile Thread _activitySwitch; 
	
	private static Activity _activity;
	private static Class _nextActivity;
	private static boolean _canceled = false;	
	private static int _delayInMillis;
	
	public ActivitySwitch(Class nextActivity)
	{
		_nextActivity = nextActivity;		
	}
	
	
	public synchronized void goToNextActivity(Activity activity, int delayInMillis) 
	{
		_activity = activity;	
		_delayInMillis = delayInMillis;
		//switchIt();
		_activitySwitch = new Thread(this);
		_activitySwitch.start();
	}

	protected  void switchIt()
	{
		
		Log.d("ActivitySwitch", "switching to..." + _nextActivity.getName());
		_activity.startActivity(new Intent(_activity.getApplicationContext(), _nextActivity));
		_activity.finish();
	}
	
	public synchronized void cancelSwitching()
	{
		if(_activitySwitch != null)
		{
			Thread tempThread= _activitySwitch;
			_activitySwitch = null;
			tempThread.interrupt();
		}		
		Log.d("ActivitySwitch", "Activity switch was canceled now");
	}


	@Override
	public void run() 
	{
		super.run();
		try 
		{
			int done = 0;
			while(done < _delayInMillis)
			{
				sleep(100);
				done += 100;
			}
			
		} 
		catch (InterruptedException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(_activitySwitch == Thread.currentThread())
		{
			switchIt();
		}
		else
		{
			Log.d(this.getClass().getName(), "Thread was interuppted before it can be completely executed");
		}
	}
}
